package com.example.mqspring.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

public class RabbitMqUtil {

    public static final String queue = "bobotest";
    public static final String exchange = "myexchange";
    public static Connection createConnection( ){
//        创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = null;
        try {
            factory.setHost("192.168.100.128");
            factory.setPort(5672);
            factory.setVirtualHost("bobo");
            factory.setUsername("guest");
            factory.setPassword("guest");
            connection = factory.newConnection();
            //          获取信道
//            channel  = connection.createChannel();
//            定义队列
//            channel.queueDeclare(myQueue, true, false,false,null);
        } catch (Exception e) {
            System.out.println("URI解析出错");
            e.printStackTrace();
        }
        return connection;
    }
    public static void bindQueue(Channel channel, String myExchangge, String...queue) {
        try {
            for (String que:queue) {
                channel.queueDeclare(que,false,false,false,null);
                channel.queueBind(que,myExchangge,"");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendMessage(Channel channel,String type, String Myexchange, String routkey, String message) throws Exception {

        channel.exchangeDeclare(Myexchange,type,false,false,null);
        channel.basicPublish(Myexchange,routkey,null,message.getBytes());
    }

    public static Channel declareConsumer(String queue,String type,Channel channel, String MyExchange, String routingkey) throws Exception {
        channel.exchangeDeclare(MyExchange,type,false,false,null);
        channel.queueDeclare(queue,false,false,false,null);
        channel.queueBind(queue,MyExchange,routingkey);
        return channel;
    }
}
